<template>
  <div class="editor-container">
    <div class="prop-edit">
    <a-button type="primary" @click="addRect()" style="margin: 8px;"> 添加矩形</a-button>
    <a-button type="primary" @click="addCircle()" style="margin: 8px;"> 添加圆形</a-button>
    <a-button type="primary" @click="addTrapezoid()" style="margin: 8px;"> 添加线段</a-button>
    <div v-if="selectItem?.attrs?.stroke" style="display: flex;">
      <div  style="margin: 8px; "> 边框颜色：<input type="color" v-model="selectItem.attrs.stroke" @input="changeColor($event)"></div>
      <a-button type="danger" @click="deleteItem()" style="margin: 8px;  width: 200px;"> 删除</a-button>
    </div>
  </div>
  <div id="container"></div>
  </div>

</template>

<script lang="ts">
import { defineComponent, PropType, onMounted, ref, watch } from 'vue';
import type { IPreset } from './types'
import Konva from 'konva';
import { message } from 'ant-design-vue';
declare global {
  interface Window {
    getEnv: (name: string) => any;
    confirmEdit: () => void;
    cancelEdit: () => void;
  }
}
export default defineComponent({
  props: {
    basicPropsValue: {
      type: Object as PropType<{ width: number, height: number }>,
      default: () => ({ width: 900, height: 600 })
    },
    preset: { type: Object as PropType<IPreset>, default: () => { data: [] } },
    onValueUpdated: { type: Function as PropType<(v: IPreset) => void> }
  },
  setup(props) {
    const editingPreset = ref({} as IPreset);
    const stage = ref(null as null | any)
    const layer = ref(null as null | any)
    const tr = ref (null as null | any )
    const markNumber = ref(1)
    const selectItem = ref()
    onMounted(() => {
      if (props.preset) {
        editingPreset.value = JSON.parse(JSON.stringify(props.preset));
      }
      stage.value = new Konva.Stage({
        container: 'container',
        width: 800,
        height: 530,
      });
      layer.value = new Konva.Layer();
      stage.value.add(layer.value)
      initRender()
      handleAddEventListent()
    });
    const itemRect = {
      "x": 70,
      "y": 70,
      "stroke": "deeppink",
      "strokeWidth": 2,
      "height": 100,
      "width": 100,
      "name": "rect",
      "draggable": true,
      "rotation": 0,
      "scaleX": 1,
      "scaleY": 1,
      "skewX": 0,
      "skewY": 0
    }
    const itemCircle = {
      "name": "circle",
      "x": 300,
      "y": 140,
      "radius": 70,

      "stroke": "deeppink",
      "strokeWidth": 2,
      "draggable": true,
      "rotation": 0,
      "scaleX": 1,
      "scaleY": 1,
      "skewX": 0,
      "skewY": 0
    }
    const itemTrapezoid = {
      "id":"trapezoid",
        "x":90,
        "y":90,
        "stroke":"lightgreen",
        "points":[100,90,100, 100,  300, 100 ,300,90 ],
        "strokeWidth":2,
        "name":"trapezoid",
        "draggable":true,
        "rotation":0,
        "scaleX":1,
        "scaleY":1,
        "skewX":0,
        "skewY":0
    }
    watch(markNumber, () => {
      let newData = [] as Array<any>
      layer.value.children.forEach(item => {
        if (item.className !== "Transformer") {
          const { attrs } = item
          newData.push(attrs)
        }
      })


      if (props.onValueUpdated) {
        editingPreset.value.data = newData
        props.onValueUpdated(JSON.parse(JSON.stringify(editingPreset.value)));
      }
    }, { deep: true });
    function handleAddEventListent() {
      if (stage.value == null) return
      stage.value.on('click tap', function (e) {
        if (e.target.nodeType == "stage") {
          stage.value.find('Transformer').destroy();
          selectItem.value = null
          layer.value.draw();
          return;
        }
        if (stage.value.find('Transformer').length) {
          stage.value.find('Transformer').forEach(item => {
            item.destroy()
          })
        }

        
        if (e.target.nodeType != "stage") {
          tr.value = new Konva.Transformer();
        layer.value.add(tr.value);
        console.log(e.target);
        
        tr.value.attachTo(e.target);
        selectItem.value = e.target
        }
        
        layer.value.draw();
      });
    }
    function initRender() {
      editingPreset.value.data.forEach(item => {
        if (item.name == "rect") {
          const { id, x, y, stroke, strokeWidth, height, width, name, draggable, rotation, scaleX, scaleY, skewX, skewY } = item
          const rect = createCircle(id, x, y, stroke, strokeWidth, height, width, name, draggable, rotation, scaleX, scaleY, skewX, skewY)
          layer.value.add(rect)
          addEventDragEnd(rect)
          addEventTransformend(rect)
        } else if (item.name == "circle") {
          const { id, x, y, stroke, strokeWidth, radius, name, draggable, rotation, scaleX, scaleY, skewX, skewY } = item
          const circle = createRect(id, x, y, stroke, strokeWidth, radius, name, draggable, rotation, scaleX, scaleY, skewX, skewY)
          layer.value.add(circle)
          addEventDragEnd(circle)
          addEventTransformend(circle)
        } else  if(item.name == 'trapezoid'){
          const { id, x, y, stroke, strokeWidth, points, name, draggable, rotation, scaleX, scaleY, skewX, skewY } = item
         const trapezoid = createTrapezoid(id, x, y, stroke, strokeWidth, points, name, draggable, rotation, scaleX, scaleY, skewX, skewY )
          layer.value.add(trapezoid)
          addEventDragEnd(trapezoid)
          addEventTransformend(trapezoid)
        }
      })
    }
    function addEventDragEnd(node) {
      node.on('dragend', () => {
        markNumber.value++
      })
    }
    function addEventTransformend(node) {
      node.on('transformend', () => {
        markNumber.value++
      })
    }
    function createCircle(id, x, y, stroke, strokeWidth, height, width, name, draggable, rotation, scaleX, scaleY, skewX, skewY) {
      return new Konva.Rect({
        id,
        x: x,
        y: y,
        width: width,
        height: height,
        stroke: stroke,
        strokeWidth: strokeWidth,
        name: name,
        draggable: draggable,
        rotation: rotation, scaleX: scaleX, scaleY: scaleY, skewX: skewX, skewY: skewY
      });

    }
    function createRect(id, x, y, stroke, strokeWidth, radius, name, draggable, rotation, scaleX, scaleY, skewX, skewY) {
      return new Konva.Circle({
        id,
        x: x,
        y: y,
        radius: radius,
        stroke: stroke,
        strokeWidth: strokeWidth,
        name: name,
        draggable: draggable,
        rotation: rotation, scaleX: scaleX, scaleY: scaleY, skewX: skewX, skewY: skewY
      });
    }
    function createTrapezoid (id, x, y, stroke, strokeWidth, points, name, draggable, rotation, scaleX, scaleY, skewX, skewY ){
    // const left =  new Konva.Line({
    //     id,
    //     x: x,
    //     y: y,
    //     closed:true,
    //     points:[100,100,100,90],
    //     stroke: stroke,
    //     strokeWidth: strokeWidth,
    //     name: name,
    //     draggable: false,
    //     rotation: rotation, scaleX: scaleX, scaleY: scaleY, skewX: skewX, skewY: skewY
    //   })
    //   const right =  new Konva.Line({
    //     id,
    //     x: x,
    //     y: y,
    //     closed:true,
    //     points:[300,100,300,90],
    //     stroke: stroke,
    //     strokeWidth: strokeWidth,
    //     name: name,
    //     draggable: false,
    //     rotation: rotation, scaleX: scaleX, scaleY: scaleY, skewX: skewX, skewY: skewY
    //   })
      const line =  new Konva.Line({
        id,
        x: x,
        y: y,
        closed:false,
        points:points,
        stroke: stroke,
        strokeWidth: strokeWidth,
        name: name,
        draggable: draggable,
        rotation: rotation, scaleX: scaleX, scaleY: scaleY, skewX: skewX, skewY: skewY
        });
        // const group = new Konva.Group({
        //   x: x,
        //   y: y,
        //   width:300,
        //   height:40,
        //   name: name,
        //   draggable: draggable,
        //   rotation: rotation, scaleX: scaleX, scaleY: scaleY, skewX: skewX, skewY: skewY
        // })
        // group.add(left)
        // group.add(right)
        // group.add(line)
        return line
    }
    const rectIndex = ref(2)
    const circleIndex = ref(2)
    const trapezoidIndex = ref(2)
    function addRect() {
      let { x, y, stroke, strokeWidth, height, width, name, draggable, rotation, scaleX, scaleY, skewX, skewY } = itemRect
      x = x + 5
      y = y + 5
      const id = `rect${rectIndex.value}`
      const rect = createCircle(id, x, y, stroke, strokeWidth, height, width, name, draggable, rotation, scaleX, scaleY, skewX, skewY)
      rectIndex.value++
      layer.value.add(rect)
      addEventDragEnd(rect)
      addEventTransformend(rect)
    }
    function addCircle() {
      let { x, y, stroke, strokeWidth, radius, name, draggable, rotation, scaleX, scaleY, skewX, skewY } = itemCircle
      x = x + 5
      y = y + 5
      const id = `circle${circleIndex.value}`
      const circle = createRect(id, x, y, stroke, strokeWidth, radius, name, draggable, rotation, scaleX, scaleY, skewX, skewY)
      circleIndex.value++
      layer.value.add(circle)
      addEventDragEnd(circle)
      addEventTransformend(circle)
    }
    function addTrapezoid (){
      
      let {  x, y, stroke, strokeWidth, points, name, draggable, rotation, scaleX, scaleY, skewX, skewY } = itemTrapezoid
        const id = `trapezoid${trapezoidIndex.value}`
        x = x + 5
        y = y + 5
         const trapezoid = createTrapezoid(id, x, y, stroke, strokeWidth, points, name, draggable, rotation, scaleX, scaleY, skewX, skewY )
         trapezoidIndex.value++
         layer.value.add(trapezoid)
          addEventDragEnd(trapezoid)
          addEventTransformend(trapezoid)
    }
    function changeColor (event){

      selectItem.value.stroke(event.target.value)
    
      layer.value.draw();
      markNumber.value++

    }
    function deleteItem(){
      if(selectItem.value.attrs.stroke) {
        selectItem.value.destroy()
        stage.value.find('Transformer').forEach(item => {
            item.destroy()
          })
      layer.value.draw()
      markNumber.value++
      
      }
     
    }
    return {
      editingPreset,
      selectItem,
      addRect,
      addCircle,
      changeColor,
      deleteItem,
      addTrapezoid
    };
  }
})
</script>

<style lang="less" scoped>
.editor-container {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%,-50%);
  box-shadow: 0 0 20px 2px gray;
}
#container {
  border: 1px solid #ccc;
}
.prop-edit {
  display: flex;
  width: 800px;
  // height: 80vh;
  background-color: antiquewhite;
}
</style>